package com.hc.core.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ReflectTool {

	/**
	 * 将查询到的参数封装到实体Bean
	 * 
	 * @param array
	 * @param object
	 * @param newClass
	 * @throws SQLException
	 */
	public static void transformToBean(ResultSet rs, String tableName,
			Object object, Class objectClass) throws SQLException {
		String columns = PropertiesTool.getInstance().getPropertiesValue(
				tableName);
		String[] array = columns.split(",");
		if (array != null) {
			for (int m = 0; m < array.length; m++) {
				String columnName = array[m];
				Object columnValue = null;

				Class type = null;
				Method method = findMethod("get" + columnName, objectClass);
				if (method != null) {
					type = method.getReturnType();
				}
				if (type.equals(java.lang.String.class)) {
					columnValue = rs.getString(columnName);
				} else if (type.equals(java.util.Date.class)) {
					columnValue = rs.getDate(columnName);
				} else if (type.equals(java.lang.Integer.class)) {
					columnValue = rs.getInt(columnName);
				}
				System.out.println("columnName : " + columnName + "  type: "
						+ type);
				invokeMeth(columnName, object, columnValue, objectClass);
			}
		}
	}

	/**
	 * 调用set方法
	 * 
	 * @param cloname
	 * @param instance
	 * @param obj
	 * @param clazz
	 */
	public static void invokeMeth(String cloname, Object instance, Object obj,
			Class clazz) {
		try {
			Method m = findMethod("set" + cloname, clazz);
			if (m != null)
				m.invoke(instance, obj);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * 查询是否存在列名对应的方法
	 * 
	 * @param name
	 * @param clazz
	 * @return
	 */
	public static Method findMethod(String name, Class clazz) {
		Method[] m = clazz.getMethods();

		for (int i = 0; i < m.length; i++) {
			if (name.equalsIgnoreCase(m[i].getName()))
				return m[i];
		}
		return null;
	}

}
